#include "core/compiler/compiler_manager.h"
#include <QDir>
#include <QStandardPaths>
#include <QDebug>

CompilerManager::CompilerManager(QObject *parent)
    : QObject(parent), currentProcess(nullptr) {
    detectCompilers();
}

CompilerManager::~CompilerManager() {
    if (currentProcess) {
        currentProcess->kill();
        currentProcess->deleteLater();
    }
}

void CompilerManager::detectCompilers() {
    // 检测C编译器 (gcc或clang)
    QString cCompiler = QStandardPaths::findExecutable("gcc");
    if (cCompiler.isEmpty()) {
        cCompiler = QStandardPaths::findExecutable("clang");
    }
    
    if (!cCompiler.isEmpty()) {
        compilers[C] = {cCompiler, {"-Wall", "-Wextra", "-std=c11"}};
    }
    
    // 检测C++编译器 (g++或clang++)
    QString cppCompiler = QStandardPaths::findExecutable("g++");
    if (cppCompiler.isEmpty()) {
        cppCompiler = QStandardPaths::findExecutable("clang++");
    }
    
    if (!cppCompiler.isEmpty()) {
        compilers[CPP] = {cppCompiler, {"-Wall", "-Wextra", "-std=c++17"}};
    }
    
    // 检测Node.js (用于JavaScript/TypeScript)
    QString nodePath = QStandardPaths::findExecutable("node");
    if (!nodePath.isEmpty()) {
        compilers[JavaScript] = {nodePath, {}};
        
        // 检测TypeScript编译器 (tsc)
        QString tscPath = QStandardPaths::findExecutable("tsc");
        if (!tscPath.isEmpty()) {
            compilers[TypeScript] = {tscPath, {}};
        }
    }
    
    // 检测Python
    QString pythonPath = QStandardPaths::findExecutable("python3");
    if (pythonPath.isEmpty()) {
        pythonPath = QStandardPaths::findExecutable("python");
    }
    
    if (!pythonPath.isEmpty()) {
        compilers[Python] = {pythonPath, {}};
    }
}

bool CompilerManager::compile(const QString &sourceFile, Language language, const QString &outputFile) {
    if (!compilers.contains(language)) {
        emit compilationFinished(false, "No compiler available for this language");
        return false;
    }
    
    if (currentProcess) {
        currentProcess->kill();
        currentProcess->deleteLater();
    }
    
    currentProcess = new QProcess(this);
    outputBuffer.clear();
    
    connect(currentProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &CompilerManager::onProcessFinished);
    connect(currentProcess, &QProcess::readyReadStandardOutput,
            this, &CompilerManager::onReadyReadStandardOutput);
    connect(currentProcess, &QProcess::readyReadStandardError,
            this, &CompilerManager::onReadyReadStandardError);
    
    CompilerInfo info = compilers[language];
    QStringList arguments = info.defaultArgs;
    
    if (language == C || language == CPP) {
        arguments << "-o" << (outputFile.isEmpty() ? QFileInfo(sourceFile).baseName() : outputFile);
    }
    
    arguments << sourceFile;
    
    emit compilationStarted();
    currentProcess->start(info.compilerPath, arguments);
    
    return true;
}

bool CompilerManager::hasCompiler(Language language) const {
    return compilers.contains(language);
}

void CompilerManager::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) {
    Q_UNUSED(exitStatus);
    
    bool success = (exitCode == 0);
    emit compilationFinished(success, outputBuffer);
    
    currentProcess->deleteLater();
    currentProcess = nullptr;
}

void CompilerManager::onReadyReadStandardOutput() {
    outputBuffer += currentProcess->readAllStandardOutput();
}

void CompilerManager::onReadyReadStandardError() {
    outputBuffer += currentProcess->readAllStandardError();
}

QString CompilerManager::getCompilerName(Language language) const {
    switch (language) {
    case C: return "C Compiler";
    case CPP: return "C++ Compiler";
    case JavaScript: return "JavaScript Engine";
    case TypeScript: return "TypeScript Compiler";
    case Python: return "Python Interpreter";
    default: return "Unknown";
    }
}